// routes/rag.js
const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth'); // 引入认证中间件

// 引入日志工具
const logger = require('../utils/logger');

// 引入向量存储服务
const { searchKnowledgePoints } = require('../../services/vectorStoreService');

// @route   POST /api/rag/search
// @desc    基于用户查询搜索相关知识点
// @access  Private (需要登录)
router.post('/search', auth, async (req, res) => {
    try {
        const { query, k = 4 } = req.body;
        const userId = req.user.id;
        
        logger.route('RAG_SEARCH', 'Received RAG search request', { userId, query });
        
        if (!query) {
            logger.warn('RAG_SEARCH', 'Query is required');
            return res.status(400).json({ msg: 'Query is required' });
        }

        // 执行向量搜索
        const results = await searchKnowledgePoints(query, k);
        
        logger.info('RAG_SEARCH', 'RAG search completed successfully', { userId, resultCount: results.length });
        res.json(results);
    } catch (err) {
        logger.error('RAG_SEARCH', 'Server error during RAG search', err);
        res.status(500).send('Server Error');
    }
});

module.exports = router;